<?php

namespace App\Http\Controllers\Api;


use Doctrine\DBAL\Driver\AbstractDB2Driver;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;

use EasyWeChat\Factory;



class WechatPayController extends Controller
{


    protected $config;
    protected $payment;

    public function __construct()
    {
        $this->config = [
            'app_id' => 'wx2ac5615f35ce3ee1',

            'mch_id' => '1699304091', // 微信支付MCHID 商户收款账号
            'key' => 'lanbangyoupin123lanbangyoupin123', // 微信支付KEY



            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => '/www/wwwroot/lanbang/public/wx1/apiclient_cert.pem', // XXX: 绝对路径！！！！
            'key_path'           => '/www/wwwroot/lanbang/public/wx1/apiclient_key.pem',      // XXX: 绝对路径！！！！
            //'cert_path'          => 'E:\Download/apiclient_cert.pem', // XXX: 绝对路径！！！！
            //'key_path'           => 'E:\Download/apiclient_key.pem',      // XXX: 绝对路径！！！！

            'notify_url'         => '',     // 你也可以在下单时单独设置来想覆盖它

        ];
        $this->payment = Factory::payment($this->config);
        //$this->payment->setSubMerchant('1610272040');  // 子商户 AppID 为可选项

    }

    //预支付订单  type 1扫码订单  2充值订单
    public function prepayOrder($order_id,$openid){



        $order = DB::table('order')->find($order_id);
        $str = "兰蚌优品订单";


        if(!$order){
            return false;
        }

        $result = $this->payment->order->unify([
            'body' => $str,
            'out_trade_no' => $order->order_sn,
            'total_fee' => $order->money*100,
            //'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => 'https://lbyp.hmisp.cn/api/v1/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openid,
        ]);

        if(isset($result['prepay_id'])){
            return $this->signAgain($result['prepay_id']);

        }else{
            return $result;
        }

// $result:
//{
//    "return_code": "SUCCESS",
//    "return_msg": "OK",
//    "appid": "wx2421b1c4390ec4sb",
//    "mch_id": "10000100",
//    "nonce_str": "IITRi8Iabbblz1J",
//    "openid": "oUpF8uMuAJO_M2pxb1Q9zNjWeSs6o",
//    "sign": "7921E432F65EB8ED0CE9755F0E86D72F2",
//    "result_code": "SUCCESS",
//    "prepay_id": "wx201411102639507cbf6ffd8b0779950874",
//    "trade_type": "JSAPI"
//}

    }




    public function signAgain($prepayId){
        $jssdk = $this->payment->jssdk;
        $config = $jssdk->bridgeConfig($prepayId, false); // 返回数组

        return $config;
    }
//    public function test(){
//        update_pay_status([]);
//    }
    public function notify(){

       // $message = json_decode('{"appid":"wx39cfc8f72f898ccd","bank_type":"OTHERS","cash_fee":"10","fee_type":"CNY","is_subscribe":"N","mch_id":"1616722309","nonce_str":"61a97e561148d","openid":"oYUDb5LbaoS79Tvb72U3r9t32Dy0","out_trade_no":"recharge16384978785376","result_code":"SUCCESS","return_code":"SUCCESS","sign":"21ADE1C604128214DAC2162BA9553054","time_end":"20211203101805","total_fee":"10","trade_type":"JSAPI","transaction_id":"4200001307202112035938203642"}',true);
        //update_pay_status($message);die;
        $response =$this->payment->handlePaidNotify(function($message, $fail){
            //file_put_contents("/www/wwwroot/gift/pay.log",date("Y-m-d H:i:s").'-data-'.json_encode($message)."\r\n",FILE_APPEND);


            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
//            $order_sn = $message['out_trade_no'];
//            $order = Db::name('order')->where('order_sn',$order_sn)->find();
//
//            if (!$order || $order['']) { // 如果订单不存在 或者 订单已经支付过了
//                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
//            }

            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////


            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                //file_put_contents("/www/wwwroot/gift/pay.log",date("Y-m-d H:i:s").'-return_code-'."\r\n",FILE_APPEND);

                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
//                    $order->paid_at = time(); // 更新支付时间为当前时间
//                    $order->status = 'paid';
                    //file_put_contents("/www/wwwroot/gift/pay.log",date("Y-m-d H:i:s").'-result_code-'."\r\n",FILE_APPEND);

                    update_pay_status($message);
                    // 用户支付失败
                } elseif ($message['result_code'] === 'FAIL') {
//                    $order->status = 'paid_fail';
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

//            $order->save(); // 保存订单

            return true; // 返回处理完成
        });

        return $response->send(); // return $response;
    }

    public function refund($order){

        $refund_no = date('YmdHis',time()).rand(1000,9999);
        // 参数分别为：商户订单号、商户退款单号、订单金额、退款金额、其他参数
        $result = $this->payment->refund->byOutTradeNumber($order['order_sn'], $refund_no, $order['money']*100, $order['money']*100, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '订单退款',
        ]);


        return $result;
    }


    //企业付款到零钱
    public function toBalance($id,$openid){

        $withdrawal = DB::table('withdrawals')->find($id);
        if(!$withdrawal) return false;

        $res = $this->payment->transfer->toBalance([
            'partner_trade_no' => $withdrawal->id, // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid' => $openid,
            'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            //'re_user_name' => '王小帅', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount' => $withdrawal->money*100, // 企业付款金额，单位为分
            'desc' => '提现', // 企业付款操作说明信息。必填
        ]);
        return $res;
    }

    public function test(){
        $message = json_decode('{"appid":"wxa0a4e4c7ca0b93ad","bank_type":"OTHERS","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1507346331","nonce_str":"61386150d7771","openid":"oxjr85ZE7wyrDrqMFN3mMtgjMR_o","out_trade_no":"recharge16310848809628","result_code":"SUCCESS","return_code":"SUCCESS","sign":"FEE2F0AF66DFD486DAF0BA0DCB3D944A","time_end":"20210908150824","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200001222202109088152219411"}',true);
        update_pay_status($message);
    }

}
